<?php
/**
 * Created by PhpStorm.
 * User: divya
 * Date: 2018/8/3
 * Time: 下午2:55
 */

namespace app\api\service;


use app\api\model\Product;
use app\api\model\UserAddress;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;

class Order
{
//    订单的商品列表，也就是客户端传递过来的products参数
    protected $oproducts;
    protected $products;
    protected $uid;
    protected function place($uid, $oproducts)
    {

        $this->oproducts = $oproducts;
        $this->products = $this->getProductsByOrder($oproducts);
        $this->uid = $uid;
        $status = $this->getOrderStatus();
        if (!$status['pass']){
            $status['order_id'] = -1;
            return $status;
        }
//        开始创建订单
        $orderSnap = $this->snapOrder();
    }
//    生成订单快照
    private function snapOrder($status){
        $snap = [
            'orderPrice'=>0,
            'totalCount'=>0,
            'pStatus'=>[],
            'snapAddress'=>null,
            'snapName'=>'',
            'snapImage'=>''
        ];
        $snap['orderPrice'] = $status['orderPrice'];
        $snap['totalCount'] = $status['totalCount'];
        $snap['pStatus'] = $status['pStatusArray'];
        $snap['snapAddress']= json_encode($this->getUserAddress());
        $snap['snapName'] = $this->products[0]['name'];
        $snap['snapImage'] = $this->products[0]['main_img_url'];
        if (count($this->products)>1){
            $snap['snapName'] .= '等';
        }
    }
    private function getUserAddress(){
        $userAddress = UserAddress::where('user_id','=',$this->uid)
            ->find();
        if (!$userAddress){
            throw new UserException([
                'msg'=>'用户收获地址不存在，下单失败',
                'errorCode'=>6001
            ]);
        }
        return $userAddress->toArray();

    }

    private function getOrderStatus()
    {
        $status = [
            'pass' => true,
            'orderPrice' => 0,
            'pStatusArray' => []
        ];
        foreach ($this->oproducts as $oProduct) {
            $pStatus = $this->getPruductStatus(
                $oProduct['product_id'],$oProduct['count'],$this->products
            );
            if (!$pStatus['haveStock']){
                $status['pass'] = false;
            }
            $status['orderPrice'] += $pStatus['totalPrice'];
            $status['totalCount'] += $pStatus['totalCount'];
            array_push($status['pStatusArray'],$status);
        }
    }

    private function getPruductStatus($oPID, $oCount, $products)
    {
        $pIndex = -1;
        $pStatus = [
            'id' => null,
            'haveStock' => false,
            'count' => 0,
            'name' => '',
            'pStatusArray' => 0
        ];
        for ($i = 0; i < count($products); $i++) {
            if ($oPID == $products[$i]['id']) {
                $pIndex = $i;
            }
        }
        if ($pIndex == -1){
            throw new OrderException([
                'msg'=>'id为'.$oPID.'商品不存在，创建订单失败'
            ]);
        }else{
            $product = $products[$pIndex];
            $pStatus['id'] = $products[$i]['id'];
            $pStatus['name'] = $product['name'];
            $pStatus['count'] = $oCount;
            $pStatus['totalPrice'] = $product['price'] * $oCount;
            if ($product['stock']-$oCount >= 0){
                $pStatus['haveStock'] = true;
            }else{
                $pStatus['haveStock'] = false;
            }
        }
        return $pStatus;

    }

    // 根据订单信息查找真实的商品信息
    private function getProductsByOrder($oproducts)
    {
        $oPIDs = [];
        foreach ($oproducts as $item) {
            array_push($oPIDs, $item['product_id']);
        }
        $products = Product::all($oPIDs)
            ->visible(['id', 'price', 'stock', 'name', 'main_img_url'])
            ->toArray();
        return $products;
    }
}